package com.cn.transfer.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.jiandaoyun.*;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author: weidian
 * @date: 2024/7/31 17:23
 * @Description: 预付款金额修改采购订单
 */
@RestController
@Slf4j
public class FuKuandanController {
    private final ResourceLoader resourceLoader;

    private static final String SECRET = "ERsdfSFWERDSFDSd";
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    public FuKuandanController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private static final int CORE_POOL_SIZE = 20;         // 核心线程数
    private static final int MAXIMUM_POOL_SIZE = 50;     // 最大线程数
    private static final long KEEP_ALIVE_TIME = 60L;      // 空闲线程存活时间
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // 存活时间单位
    private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(150); // 任务队列

    // 创建自定义线程池
    private static ExecutorService threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TIME_UNIT,
            WORK_QUEUE,
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
    );

    @PostMapping("/YuFukuanCalculation")
    public String callback(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        //log.info("存货申请=====" + payload);
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        threadPool.submit(() -> handleData(payload));

        return "success";
    }
    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, FuKuandanController.SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }
    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_UPDATE.equals(op)) {
            create(data,true);
        }else if (DATA_DELETE.equals(op)) {
            create(data,false);
        }
    }
    private void create(String data,boolean fale) {
        Header[] headers = ConnmeUtils.createHeaders();
        Fukuandan fukuandan = JSONUtil.toBean(data, Fukuandan.class);
        if (fale){
            if (fukuandan.getFlowState()!=1){
                return;
            }
        }
        Map<String, Map<String,Double>> yushou = new HashMap<>();
        Map<String,  Map<String,Double>> weikuan = new HashMap<>();


        for (Fukuandan.Yufu yufu : fukuandan.get_widget_1721546510495()) {
            if (yushou.containsKey(yufu.get_widget_1721546510504())){
                Map<String, Double> stringDoubleMap = yushou.get(yufu.get_widget_1721546510504());
                if (stringDoubleMap.containsKey(yufu.get_widget_1721616942683())){
                    Double aDouble = yushou.get(yufu.get_widget_1721546510504()).get(yufu.get_widget_1721616942683());
                    stringDoubleMap.put(yufu.get_widget_1721616942683(),yufu.get_widget_1721546510520()+aDouble);
                }else {
                    stringDoubleMap.put(yufu.get_widget_1721616942683(),yufu.get_widget_1721546510520());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(yufu.get_widget_1721616942683(),yufu.get_widget_1721546510520());
                yushou.put(yufu.get_widget_1721546510504(),yushou001);
            }
        }
        chuliYuSuan(headers, yushou,true,fale);

        for (Fukuandan.Weikuan yufu :  fukuandan.get_widget_1721548605263()) {
            if (weikuan.containsKey(yufu.get_widget_1722047128214())){
                Map<String, Double> stringDoubleMap = weikuan.get(yufu.get_widget_1722047128214());
                if (stringDoubleMap.containsKey(yufu.get_widget_1722047128215())){
                    Double aDouble = weikuan.get(yufu.get_widget_1722047128214()).get(yufu.get_widget_1722047128215());
                    stringDoubleMap.put(yufu.get_widget_1722047128215(),yufu.get_widget_1721548605266()+aDouble);
                }else {
                    stringDoubleMap.put(yufu.get_widget_1722047128215(),yufu.get_widget_1721548605266());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(yufu.get_widget_1722047128215(),yufu.get_widget_1721548605266());
                weikuan.put(yufu.get_widget_1722047128214(),yushou001);
            }
        }

        chuliYuSuan(headers, weikuan,false,fale);

    }

    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan,boolean ister,boolean fale) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
                parameterCxv.put("entry_id", "669df675b02f2a74e35ca2f9");

                log.info("Processing innerMap: " + innerMap);
                innerMap.forEach((innerKey, value) -> {
                    HashMap<String, String > communti=new HashMap<>();

                    communti.put("_widget_1721628277543",key);
                    communti.put("_widget_1721628277558",innerKey);
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCxv, headers,communti , SAPPurchaseOrder.class);
                    log.info("Processing inner key: " + innerKey + ", value: " + value);
                    SAPPurchaseOrder salesOrderKu = sapPurchaseOrders.get(0);
                    if (salesOrderKu == null) {
                        log.error("SalesOrderKu is null for key: " + key);
                        return;
                    }


                    if (ister) {
                        if (fale){
                            if (salesOrderKu.get_widget_1722475785244() == null) {
                                salesOrderKu.set_widget_1722475785244(value);
                            } else {
                                salesOrderKu.set_widget_1722475785244(value + salesOrderKu.get_widget_1722475785244());
                            }
                        }else {
                            if (salesOrderKu.get_widget_1722475785244() == null) {
                                log.info("累计预付是空，无法在递减");
                            } else {
                                salesOrderKu.set_widget_1722475785244(value - salesOrderKu.get_widget_1722475785244());
                            }
                        }
                    } else {
                        if (fale){
                            if (salesOrderKu.get_widget_1722475785245() == null) {
                                salesOrderKu.set_widget_1722475785245(value);
                            } else {
                                salesOrderKu.set_widget_1722475785245(value + salesOrderKu.get_widget_1722475785245());
                            }
                        }else {
                            if (salesOrderKu.get_widget_1722475785245() == null) {
                                log.info("累计尾款是空，无法在递减");
                            } else {
                                salesOrderKu.set_widget_1722475785245(value - salesOrderKu.get_widget_1722475785245());
                            }
                        }

                    }
                    if (salesOrderKu.get_widget_1722475785244() != null && salesOrderKu.get_widget_1722475785245() != null){
                        salesOrderKu.set_widget_1722475785243(salesOrderKu.get_widget_1721629214721()-salesOrderKu
                                .get_widget_1722475785244()-salesOrderKu.get_widget_1722475785245());
                    }

                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
                    parameterInster.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterInster.put("is_start_trigger", "true");
                    parameterInster.put("data_id", sapPurchaseOrders.get(0).get_id());
                    sapPurchaseOrders.get(0).set_id(null);
                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.get(0)));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    log.info("Modified sales order prepayment: " + jsonSale);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);

                });

            } catch (Exception e) {
                log.error("Error processing key: " + key, e);
            }
        });


    }
}
